package com.swgk.core.base.model.factory;

import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.CacheRequest;
import java.nio.charset.Charset;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.mmkvutil.DatalUtils;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/**
 * @author 张驰
 * @date 2021/9/1 22:33
 * @Description 网络拦截器层处理Http网络缓存
 * @name com.swgk.core.base.model.factory
 */
public class CacheHttpInternal {

    /**
     * 根据请求获取响应
     *
     * @param request
     * @return
     * @throws IOException
     */
    public Response get(Request request) throws IOException {
        long time = System.currentTimeMillis();
        String key = "";
        if ("POST".equals(request.method())){
            key = getParamContent(request.body());
        }else{
            key = request.url().toString();
        }
        String cacheData = DatalUtils.getInstance().getData(MkvUtils.CacheModular, key);
        if (TextUtils.isEmpty(cacheData)) {
            return null;
        }
        return setResponse(request,cacheData).newBuilder().sentRequestAtMillis(time).build();
    }

    /**
     * 存储网络响应 并返回缓存的请求
     *
     * @param response
     * @return
     * @throws IOException
     */
    public CacheRequest put(Response response) throws IOException {
        String key = "";
        if ("POST".equals(response.request().method())){
            key = getParamContent(response.request().body());
        }else{
            key = response.request().url().toString();
        }
        String bodyString = getBodyString(response);
        DatalUtils.getInstance().putData(MkvUtils.CacheModular, key, bodyString);
        return null;
    }

    /**
     * 根据 Request 和缓存数据构建 Response
     * @return 返回新构建的 Request
     */
    private Response setResponse(Request request,String cacheData){
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        ResponseBody responseBody = ResponseBody.create(mediaType, cacheData);
        return new Response.Builder()
                .request(request)
                .protocol(Protocol.HTTP_1_1)
                .code(200)
                .message("")
                .body(responseBody)
                .receivedResponseAtMillis(System.currentTimeMillis())
                .build();
    }

    /**
     * 将联网数据格式化输出
     * @param response
     * @return
     * @throws IOException
     */
    public String getBodyString(Response response) throws IOException {
        ResponseBody responseBody = response.peekBody(Long.MAX_VALUE);
        Reader jsonReader = new InputStreamReader(responseBody.byteStream(), Charset.forName("UTF-8"));
        BufferedReader reader = new BufferedReader(jsonReader);
        StringBuilder sbJson = new StringBuilder();
        String line = reader.readLine();
        do {
            sbJson.append(line);
            line = reader.readLine();
        } while (line != null);
        return String.valueOf(sbJson);
    }

    /**
     * 当缓存无效的时候移除缓存
     * 比如OKHttp只支持缓存get请求，其它方法的响应不缓存
     *
     * @param request
     * @throws IOException
     */
    public void remove(Request request) throws IOException {

    }

    /**
     * 获取常规post请求参数
     */
    private String getParamContent(RequestBody body) throws IOException {
        Buffer buffer = new Buffer();
        body.writeTo(buffer);
        return buffer.readUtf8();
    }
}
